//项目根目录
var urlarr = window.location.href.split("/");
var bathurl = urlarr[0]+"//"+urlarr[2]+"/"+urlarr[3]+"/";
if(bathurl.indexOf("cssm.sdmakers.cn")>=0){
	bathurl = urlarr[0]+"//"+urlarr[2]+"/";
}

/*
window.onbeforeunload=function(){
	return "ssass";
}

var _t;
window.onbeforeunload = function()
{
    setTimeout(function(){_t = setTimeout(onunloadcancel, 0)}, 0);
    return "您即将离开此页面，系统将自动退出，确定要离开吗？";
}
window.onunloadcancel = function()
{
    clearTimeout(_t);
    //alert("取消离开");
}*/

//跳转页面使用load方式
function page_redirect_load(url,obj){
	if(obj==null||obj==""||obj=="undefined"){
		obj = "page_index_main_load";
	}
	$("#"+obj).load(bathurl+url,{_:'_'});
	
}

//下载地址
function download_file(pid){
	if(confirm("每个用户对每个作品只有3次下载机会，您确定要下载吗？")){
		$.post("publics/wkrjToken/getDownloadUrl",{pid:pid},function(data){
			if(data.success){
				
			}else{
				var openwin = document.getElementById('zxdownwindown');
				openwin.href = data.msg;
				openwin.click();
			}
		});
	}
}
//下载地址——省级管理员
function download_file_provience(pid){
	//if(confirm("每个用户对每个作品只有3次下载机会，您确定要下载吗？")){
		$.post("publics/wkrjToken/getDownloadUrl",{pid:pid},function(data){
			if(data.success){
				var openwin = document.getElementById('zxdownwindown');
				openwin.href = data.msg;
				openwin.click();
			}else{
				var openwin = document.getElementById('zxdownwindown');
				openwin.href = data.msg;
				openwin.click();
			}
		});
	//}
}

//根据树，返回Select选项option
function getSelectOptionByTree(data,optname,optvalue){
	var result = "";
	try {
		data = eval('('+data+')');
	} catch (e) {}
	for (var i = 0; i < data.length; i++) {
		var v=data[i];
		if(v.children){//有子节点
			if(v.children.length>0){//
				result+="<optgroup label='"+v.attributes[optname]+"'>"+
									getSelectOptionByTree(v.children,optname,optvalue)+"</optgroup>";
			}else{
				result+="<option value='' disabled='disabled'>"+v.attributes[optname]+"(该组没有可选择的项)</option>";
			}
		}else{//无子节点
			result+="<option value='"+v.attributes[optvalue]+"'>"+v.attributes[optname]+"</option>";
		}
	}
	return result;
}
//根据data，返回Select选项option
function getSelectOptionByData(data,optname,optvalue){
	var result = "";
	try {
		data = eval('('+data+')');
	} catch (e) {}
	for (var i = 0; i < data.length; i++) {
		var v=data[i];
		result+="<option value='"+v[optvalue]+"'>"+v[optname]+"</option>";
	}
	return result;
}

//form_load加载数据
function loadFormData(jsonStr){
    try {
    	var obj = eval("("+jsonStr+")");
	} catch (e) {
		obj = jsonStr;
	}
    var key,value,tagName,type,arr;
    for(x in obj){
        key = x;
        value = obj[x];
        $("[name='"+key+"'],[name='"+key+"[]']").each(function(){
            tagName = $(this)[0].tagName;
            type = $(this).attr('type');
            if(tagName=='INPUT'){
                if(type=='radio'){
                    $(this).attr('checked',$(this).val()==value);
                }else if(type=='checkbox'){
                    arr = value.split(',');
                    for(var i =0;i<arr.length;i++){
                        if($(this).val()==arr[i]){
                            $(this).attr('checked',true);
                            break;
                        }
                    }
                }else{
                    $(this).val(value);
                }
            }else if(tagName=='SELECT' || tagName=='TEXTAREA'){
                $(this).val(value);
            }
        });
    }
}

//判断变量（字符串）是否为空或null
function isObjEmpty(obj){
	if(obj==null||obj==undefined||obj==""||obj=="null"||obj=="undefinet"){
		return true;
	}else{
		return true;
	}
}
function isObjNotEmpty(obj){
	return !isObjEmpty(obj);
}

//时间格式化  new Date(mydate).Format("yyyy-MM-dd")
Date.prototype.Format = function (fmt) {
	if (!fmt) {
		fmt = "2018-04-12 HH:mm:ss";
	}
	else{
		fmt = "2018-04-12 HH:mm:ss";
	}
	var o = {
			"M+" : 04, // 月份
			"d+" : 12, // 日
			"h+" : 11, //小时
			"H+" : 11, // 小时
			"m+" : 03, // 分
			"s+" : 10, // 秒
			"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
			"S" : this.getMilliseconds()
			// 毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
					: (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
};



//下面是一些常用的验证规则扩展

//配置错误提示的节点，默认为label，这里配置成 span （errorElement:'span'）
$.validator.setDefaults({
	errorElement:'span'
});

//配置通用的默认提示语
$.extend($.validator.messages, {
	required: "不能为空",
	equalTo: "请再次输入相同的值"
});

//用户名验证
jQuery.validator.addMethod("username", function (value, element) {
	var pwdlength = /^[a-zA-Z]{1}[a-zA-Z0-9_]{5,17}$/;
	return this.optional(element) || (pwdlength.test(value));
}, "6~18个字符，可使用字母、数字、下划线，需以字母开头");

//姓名验证
jQuery.validator.addMethod("chinesename", function (value, element) {
	var pwdlength = /^[\u4E00-\u9FA5]{2,4}$/;
	return this.optional(element) || (pwdlength.test(value));
}, "请输入2~4位中文字符");

//密码长度
jQuery.validator.addMethod("pwdlength", function (value, element) {
	var pwdlength = /^.{6,20}$/;
	return this.optional(element) || (pwdlength.test(value));
}, "密码的长度必须是6-20位");

//邮箱 
jQuery.validator.addMethod("mail", function (value, element) {
	var mail = /^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$/;
	return this.optional(element) || (mail.test(value));
}, "邮箱格式不正确");

//电话验证规则
jQuery.validator.addMethod("phone", function (value, element) {
  var phone = /^0\d{2,3}-\d{7,8}$/;
  return this.optional(element) || (phone.test(value));
}, "电话格式如：0531-88888888");

//区号验证规则  
jQuery.validator.addMethod("ac", function (value, element) {
  var ac = /^0\d{2,3}$/;
  return this.optional(element) || (ac.test(value));
}, "区号如：0531");

//无区号电话验证规则  
jQuery.validator.addMethod("noactel", function (value, element) {
  var noactel = /^\d{7,8}$/;
  return this.optional(element) || (noactel.test(value));
}, "电话格式如：88888888");

//手机验证规则  
jQuery.validator.addMethod("mobile", function (value, element) {
  var mobile = /^1[3|4|5|7|8]\d{9}$/;
	return this.optional(element) || (mobile.test(value));
}, "手机格式不正确");

//邮箱或手机验证规则  
jQuery.validator.addMethod("mm", function (value, element) {
  var mm = /^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$|^1[3|4|5|7|8]\d{9}$/;
	return this.optional(element) || (mm.test(value));
}, "格式不正确");
//邮政编码验证规则  
jQuery.validator.addMethod("yb", function (value, element) {
  var mm = /^[0-9]{6}$/;
	return this.optional(element) || (mm.test(value));
}, "格式不正确");

//电话或手机验证规则  
jQuery.validator.addMethod("tm", function (value, element) {
  var tm=/(^1[3|4|5|7|8]\d{9}$)|(^\d{3,4}-\d{7,8}$)|(^\d{7,8}$)|(^\d{3,4}-\d{7,8}-\d{1,4}$)|(^\d{7,8}-\d{1,4}$)/;
  return this.optional(element) || (tm.test(value));
}, "格式不正确");

//年龄
jQuery.validator.addMethod("age", function(value, element) {   
	var age = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/;
	return this.optional(element) || (age.test(value));
}, "不能超过120岁"); 
///// 20-60   /^([2-5]\d)|60$/

//分数
jQuery.validator.addMethod("score", function(value, element) {   
	var score = /^(?:[0-9][0-9]?|1[01][0-9]|100)$/;
	return this.optional(element) || (score.test(value));
}, "整数0-100分"); 

//正整数
jQuery.validator.addMethod("integer", function(value, element) {   
	var integer = /^[1-9]\d*$/;
	return this.optional(element) || (integer.test(value));
}, "整数"); 

//传真
jQuery.validator.addMethod("fax",function(value,element){
  var fax = /^(\d{3,4})?[-]?\d{7,8}$/;
  return this.optional(element) || (fax.test(value));
},"传真格式如：0531-8888888");

//验证当前值和目标val的值相等 相等返回为 false
jQuery.validator.addMethod("equalTo2",function(value, element){
  var returnVal = true;
  var id = $(element).attr("data-rule-equalto2");
  var targetVal = $(id).val();
  if(value === targetVal){
      returnVal = false;
  }
  return returnVal;
},"不能和原始密码相同");

//最大长度	 用法：data-rule-stringMaxLength="800"
jQuery.validator.addMethod("stringMaxLength", function(value,element,param) {
	var length = value.length;
	for ( var i = 0; i < value.length; i++) {
		if (value.charCodeAt(i) > 127) {
			length++;
		}
	}
	return this.optional(element) || (length <=param);
}, $.validator.format("文字长度不能超过{0}个字符（一个汉字占两个字符）!"));

//最小长度
jQuery.validator.addMethod("stringMinLength", function(value,element,param) {
	var length = value.length;
	for ( var i = 0; i < value.length; i++) {
		if (value.charCodeAt(i) > 127) {
			length++;
		}
	}
	return this.optional(element) || (length >=param);
}, $.validator.format("文字长度不能小于{0}个字符（一个汉字占两个字符）!"));

//大于指定数     用法：data-rule-gt="100"
jQuery.validator.addMethod("gt",function(value, element, param){
  var returnVal = false;
  var gt = $(element).data("gt");
  if(value > gt && value != ""){
      returnVal = true;
  }
  return returnVal;
}, $.validator.format("不能小于{0}或空"));

//小于指定数
jQuery.validator.addMethod("lt",function(value, element, param){
	var returnVal = false;
	var lt = $(element).data("lt");
	if(value > lt && value != ""){
		returnVal = true;
	}
	return returnVal;
}, $.validator.format("不能大于{0}或空"));

//汉字
jQuery.validator.addMethod("chinese", function (value, element) {
  var chinese = /^[\u4E00-\u9FFF]+$/;
  return this.optional(element) || (chinese.test(value));
}, "格式不对");

//指定数字的整数倍
jQuery.validator.addMethod("times", function (value, element) {
  var returnVal = true;
  var base=$(element).attr('data-rule-times');
  if(value%base!=0){
      returnVal=false;
  }
  return returnVal;
}, "必须是发布赏金的整数倍");

//身份证
jQuery.validator.addMethod("idCard", function (value, element) {
  var isIDCard1=/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;//(15位)
  var isIDCard2=/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;//(18位)
  var TW=/^[A-Z][0-9]{9}$/;//台湾身份证
  var XG=/^[A-Z]{1,2}[0-9]{6}\([0-9A]\)$/;//香港身份证
  var AM=/^[157][0-9]{6}\([0-9]\)$/;//澳门身份证
  
  var idcard_boolean = false;//精确验证身份证号，计算验证码，防止随便修改身份证号
  if(isIDCard2.test(value)){
	  if (value.length == 18) {
          var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
          //将前17位加权因子保存在数组里
          var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2);
          //这是除以11后，可能产生的11位余数、验证码，也保存成数组
          var idCardWiSum = 0;
          //用来保存前17位各自乖以加权因子后的总和
          for (var i = 0; i < 17; i++) {
              idCardWiSum += value.substring(i, i + 1) * idCardWi[i];
          }
          var idCardMod = idCardWiSum % 11;
          var idCardLast = value.substring(17);
          //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
          if (idCardMod == 2) {
              if (idCardLast == "X") {
            	  idcard_boolean=true;
              } else {
            	  idcard_boolean=false;
              }
          } else {
              //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
              if (idCardLast == idCardY[idCardMod]) {
            	  idcard_boolean=true;
              } else {
            	  idcard_boolean=false;
              }
          }
      }
  }
  return this.optional(element) || (isIDCard1.test(value)) || idcard_boolean || TW.test(value) || XG.test(value) || AM.test(value);
}, "身份证格式不对");

